﻿//给QMS周转/串件单提交审理的数据
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Longb
//create Date:2023-04-20
//Rewriter:
//Rewrite Date:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFC.Common;
using UFC.DBUtility;
using System.Data;
using System.Text.RegularExpressions;
using System.Collections;
using System.Xml;

namespace MESQualityHistoryRecord
{
    class SendExchangeBillToQms
    {
        private const string SendExchangeBill_XmlFileds = @"exchangeName,billType,billProperty,createDate,engineType,toEngineNo,toMfgOrderName,toProductName,toDescription,drawingNo,toContainerName,specialAttribute,toLifetime,toWorkHours,toNum,reason,billSource,fromEngineNo,fromMfgOrderName,fromNum,fromProductName,fromDescription,fromContainerName,fromLifetime,isOvertake,preposerFullName,preposerDate,affiliatedFactory,checkCustomer";
        private static NewMesToQms.unifiedFunApi mtq = new NewMesToQms.unifiedFunApi();

        public void Excute()
        {
            DataTable DealFaultBill_DT = GetExchangeBillData();
            foreach (DataRow row in DealFaultBill_DT.Rows)
            {
                var resQxml = CreateXMLForExchangeBill(SendExchangeBill_XmlFileds, row);
                LogHelp.WriteLog("周转/串件单提交审理-推送XMl:" + resQxml);
                var resPxml = mtq.mesToQmsAPI(resQxml);
                LogHelp.WriteLog("周转/串件单提交审理-返回XMl:" + resPxml);
                Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",row["EXCHANGEID"].ToString ()},{"RecordType","QMS_ExchangeBill"},
                        {"ContainerID",""},{"ContainerName",""},
                        {"ProductName",row["toProductName"].ToString()},{"WorkflowStepName",""},
                        {"SendXml",resQxml},{"ResXml",resPxml}
                    };
                XmlDocument myxml = new XmlDocument();
                myxml.LoadXml(resPxml);
                string xml = myxml.SelectSingleNode("RespMsg/document").InnerText;
                myxml.LoadXml(xml);
                string success = myxml.SelectSingleNode("TETTYP/RTYPE").InnerText;//
                string message = myxml.SelectSingleNode("TETTYP/RTMSG").InnerText;//
                if (!string.IsNullOrWhiteSpace(success) && success == "S")
                {
                    recordPara.Add("IsSuccess", "0");//成功
                }
                else
                {
                    recordPara.Add("IsSuccess", "1");//失败
                    LogHelp.WriteLog(message);
                }
                OracleDAL.InserOtherSystemRecord(recordPara);
            } 
        }
        /// <summary>
        /// 获取周转/串件单数据
        /// </summary>
        /// <returns></returns>
        public DataTable GetExchangeBillData()
        {
            try
            {
                var strSql = @"SELECT e.EXCHANGEID,e.EXCHANGENAME,DECODE(e.BILLTYPE,'周转单','0','1') BILLTYPE,nvl(e.BILLPROPERTY,'周转') BILLPROPERTY,to_char(e.CREATEDATE,'yyyy-MM-dd hh24:mi:ss') CREATEDATE
                            ,e2.EMPLOYEENAME,'新机' engineType,e3.MACHINENO toEngineNo,e3.MFGORDERNAME toMfgOrderName,e3.PRODUCTNAME toProductName,e3.PRODUCTDESC toDescription
                            ,pb.productname drawingNo,p.description,e3.CONTAINERNO toContainerName,'G/Z'specialAttribute,'无'toLifetime,nvl(e.WORKHOURS,0) toWorkHours,'1'toNum
                            ,e.REASON,e.BILLSOURCE,e3.MACHINENO fromEngineNo,e3.MFGORDERNAME fromMfgOrderName,'1'fromNum,e3.PRODUCTNAME fromProductName,e3.PRODUCTDESC fromDescription,e3.CONTAINERNO fromContainerName,
                            '无'fromLifetime,'0'isOvertake,e4.FULLNAME||'/'||e4.EMPLOYEENAME  preposerFullName,to_char(sysdate,'yyyy-MM-dd hh24:mi:ss') preposerDate,u.ATTRIBUTEVALUE affiliatedFactory
                            FROM EXCHANGEBILL e 
                            LEFT JOIN EMPLOYEE e2  ON e2.EMPLOYEEID =e.EMPLOYEEID 
                            LEFT JOIN ENGINEPARTPLAN e3 ON e3.CONTAINERID =e.CONTAINERID 
                            LEFT JOIN product p ON e.productid=p.productid 
                            LEFT JOIN productbase pb ON p.productid=pb.revofrcdid
                            LEFT JOIN EMPLOYEE e4  ON e4.EMPLOYEEID =e.AUDITEMPLOYEEID 
                            LEFT JOIN USERATTRIBUTE u ON u.PARENTID =e.FACTORYID AND u.USERATTRIBUTENAME ='分厂代码'
                            left join WritetoOtherSystem ws on ws.parentid=e.EXCHANGEID and ws.recordtype='QMS_ExchangeBill'
                            WHERE e.ISUSE =0 and  nvl(e.ISARMY,0)=1 AND ws.parentid is null and rownum<500";
                DataSet myDS = OracleHelper.Query(string.Format(strSql));
                if (myDS == null)
                {
                    return null;
                }
                if (myDS.Tables.Count == 0)
                {
                    return null;
                }
                return myDS.Tables[0];
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 创建XML
        /// </summary>
        /// <param name="strList"></param>
        /// <param name="row"></param>
        /// <returns></returns>
        private string CreateXMLForExchangeBill(string strList, DataRow row)
        {
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_QMS";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            extNode.LastChild.InnerText = "MES_Send_Service";
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);

            XmlNode root = doc.CreateElement("root");
            XmlNode qmsFun = doc.CreateElement("qmsFunName");
            qmsFun.InnerText = "QMS_Send_ExchangeBill_Service";
            root.AppendChild(qmsFun);

            XmlNode documentNode = doc.CreateElement("document");
            ReqNode.AppendChild(documentNode);

            XmlNode qmsDocument = doc.CreateElement("qmsDocument");//具体业务内容
            foreach (string _key in strList.Split(','))
            {
                XmlNode mainData = doc.CreateElement(_key);
                mainData.InnerText = row.Table.Columns.Contains(_key) ? row[_key].ToString() : null;
                qmsDocument.AppendChild(mainData);
            }

            root.AppendChild(qmsDocument);
            documentNode.AppendChild(doc.CreateCDataSection("<root>" + root.InnerXml + "</root>"));
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }
    }
}
